package com.tycmc.signelectroniccontracts.logic.renzheng.qiye;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.OcrRequestParams;
import com.baidu.ocr.sdk.model.OcrResponseResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.tycmc.signelectroniccontracts.act.renzheng.qiye.FraQIyexinxi;
import com.tycmc.signelectroniccontracts.tools.base.LogicParent;
import com.tycmc.signelectroniccontracts.tools.images.UrlPath;
import com.tycmc.signelectroniccontracts.tools.net.NetUrl;
import com.tycmc.signelectroniccontracts.tools.net.NetWorkUtils;
import com.tycmc.signelectroniccontracts.tools.net.RequestAction;
import com.tycmc.signelectroniccontracts.tools.net.result.NetworkResult;
import com.tycmc.signelectroniccontracts.tools.net.tools.Json;
import com.tycmc.signelectroniccontracts.tools.other.TextShow;
import com.tycmc.signelectroniccontracts.tools.other.TyTypenum;
import com.tycmc.signelectroniccontracts.tools.show.LogShow;
import com.tycmc.signelectroniccontracts.tools.show.ProDialog;
import com.tycmc.signelectroniccontracts.tools.show.ToastShow;
import com.tycmc.signelectroniccontracts.tools.store.SharePre;
import com.tycmc.signelectroniccontracts.tools.store.SharePreName;
import com.tycmc.signelectroniccontracts.tools.times.DataTimer;

import org.json.JSONException;

import java.io.File;
import java.util.Map;

public class PreQiYeXinxi extends LogicParent {

    private  String filePath;
    private QiYeXinxiInterface pre;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            handler.sendEmptyMessageDelayed(message.what - 1, 1000);//设置1s延迟
            pre.edCode(message.what);

            return true;
        }
    });
    private FraQIyexinxi fra;

    public PreQiYeXinxi(QiYeXinxiInterface pre, String filePath) {
        this.pre = pre;
        fra = ((FraQIyexinxi) pre);
        this.filePath = filePath;
    }

    //获取验证码
    public void getcode() {
        RequestAction action = new RequestAction(NetUrl.getVerificationCode);
        action.putBody("clientArchiveNo", SharePre.getString(SharePreName.clientArchiveNo,""));
        action.putBody("verificationCodeType","1");
        final ProDialog dialog = new ProDialog(fra.getActivity(), "");
        dialog.show();
        new NetWorkUtils(fra).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                handler.sendEmptyMessage(60);
            }

            @Override
            public void failed(Object data) {
                dialog.dismiss();
                handler.sendEmptyMessage(60);
            }
        });
    }

    public void destory() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);//移除handler倒计时
        }
    }

    public void onResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TyTypenum.yingyezhizhao && resultCode == Activity.RESULT_OK) {

            if (new File(UrlPath.imagePath + CameraActivity.CONTENT_TYPE_GENERAL +filePath+ ".png").exists()) {
                pre.yingyezhizhao(UrlPath.imagePath + CameraActivity.CONTENT_TYPE_GENERAL +filePath+ ".png");
                recode(UrlPath.imagePath + CameraActivity.CONTENT_TYPE_GENERAL +filePath+ ".png");
            }

        }
    }

    private void recode(final String url) {
// 行驶证识别参数设置
        OcrRequestParams param = new OcrRequestParams();

// 设置image参数
        param.setImageFile(new File(url));

        final ProDialog dialog = new ProDialog(fra.getActivity(), "正在识别");
        dialog.show();
        OCR.getInstance(fra.getActivity()).recognizeBusinessLicense(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                // 调用成功，返回OcrResponseResult对象.
                String jsonRes = result.getJsonRes();
                LogShow.i("成功", result.getLogId() + "\n" + jsonRes);
                dialog.dismiss();
                try {
                    Map<String, Object> map = Json.getMap(jsonRes);
                    if (map.get("words_result") instanceof Map) {
                        Map wordsResult = (Map) map.get("words_result");
                        pre.initData(getWords(wordsResult, "单位名称")
                                , getWords(wordsResult, "类型")
                                , DataTimer.getStringData("yyyy-MM-dd", DataTimer.getLongTime(getWords(wordsResult, "成立日期"), "yyyy年MM月dd日"))
                                , getWords(wordsResult, "注册资本")
                                , getWords(wordsResult, "有效期")
                                , getWords(wordsResult, "社会信用代码")
                                , getWords(wordsResult, "地址")
                                , getWords(wordsResult, "经营范围")
                                , getWords(wordsResult, "法人")

                        );
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(OCRError error) {
                dialog.dismiss();
                if (new File(url).exists()) {
                    new File(url).delete();
                }
//                ToaShow.popupToast(context,error.getMessage() + "(" + error.getErrorCode() + ")");
                LogShow.i("失败", error.getLogId() + "\n" + error.getErrorCode() + "\n" + error.getMessage());
                // 调用失败，返回OCRError对象
            }
        });
    }

    private String getWords(Map map, String key) {
        String str = "";
        if (map != null) {
            if (map.get(key) instanceof Map) {
                Map map1 = (Map) map.get(key);
                return TextShow.valueOf(map1.get("words")).equals("无") ? "" : TextShow.valueOf(map1.get("words"));
            }

        }
        return str;
    }

    public void upMap(final Map upMap) {
        RequestAction action = new RequestAction(NetUrl.saveCompanyInfo);
        action.putBodyAll(upMap);
        final ProDialog dialog = new ProDialog(fra.getActivity(), "正在核对信息");
        dialog.show();
        new NetWorkUtils(fra).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                ToastShow.popupToast("企业信息上传成功");
                pre.next(upMap);
            }

            @Override
            public void failed(Object data) {
                ToastShow.popupToast(data + "");
                dialog.dismiss();
            }
        });
    }

    public interface QiYeXinxiInterface {
        void edCode(int number);//倒计时

        void yingyezhizhao(String path);

        void initData(String gongsimingcheng, String leixing, String chengliriqi, String zhuceziben, String yingyeqixian, String tongyixingyongdaima, String zhusuo, String jinyingfanwei, String farenxingming);

        void next(Map upMap);//上传成功，进行下一步
    }
}
